<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:details="{ row }">
          <el-button type="text" @click="lookView(row)">查看详情</el-button>
        </template>
        <template v-slot:groupStatus="{ row }">
          <el-switch style="display: block" v-model="row.groupStatus" @change="changegroupStatus(row)"
            active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </template>
        <template v-slot:breedType="{ row }">
          {{ breedTypeObj[row.breedType] || '--' }}
        </template>
      </TableData>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :notGroupList="notGroupList" :title="'设施划分'" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
        :facilityTypeList="facilityTypeList" :groupFacility="groupFacility" :dialogVisible="dialogVisible"
        :data="formData" />
      <el-dialog :close-on-click-modal="false" title="设施列表" :visible.sync="dialogTableVisible" width="50%"
        :before-close="handleClose">
        <el-table ref="multipleTable" :data="groupFacility" border tooltip-effect="dark" style="width: 100%">
          <el-table-column type="index" label="序号" width="55">
          </el-table-column>
          <el-table-column prop="facilityName" label="设施名称" width="120">
          </el-table-column>
          <el-table-column prop="facilityNo" label="设施编号">
          </el-table-column>
          <el-table-column prop="facilityTypeName" label="设施类型">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total="total">
      </Pagination>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import Pagination from '@/components/Pagination';
import facilityGroup from '@/api/digtalOperation/facilityGroup';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import BtnSlot from '@/components/BtnSlot';
import AddEdit from './components/addEdit';
import EnumSlot from '@/components/EnumSlot';
export default {
  components: { MainSlot, SearchForm, TableData, Pagination, BtnSlot, AddEdit, EnumSlot },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      dialogTableVisible: false,
      addEditFlag: 'add',
      btnList: ['add', 'delete'],
      formData: {},
      form: {
        cancelTime: ''
      },
      detailsInfo: {},
      searchFormData: {},
      page: 1,
      size: 10,
      total: 10,
      dataList: [],
      selectIndex: 0,
      enumList: [{
        label: "当前设施组",
        value: false
      }, {
        label: "历史设施组",
        value: true
      }],
      invcountDetailList: [],
      selectDataList: [],
      groupFacility: [],
      materialList: [],
      notGroupList: [],
      rules: {
        cancelTime: [
          { required: true, message: '请选中时间', trigger: 'blur' },
        ]
      },
      breedTypeObj: {
        "HANGING_WATER_BREED": '吊水养殖',
        "TRADITION_BREED": '传统养殖',
        "CIRCULATE_BREED": '循环水养殖',
        "RUNWAY_BREED": '跑道养殖'
      },
      tableThead: [
        { isShow: true, label: '设施组名称', prop: 'facilityGroupName', minWidth: '120px' },
        { isShow: true, label: '养殖类型', slotName: 'breedType', minWidth: '120px' },
        { isShow: true, label: '是否历史设施', slotName: 'groupStatus', minWidth: '120px' },
        { isShow: true, label: '查看设施', slotName: 'details', minWidth: '120px' },
      ],
      formItemList: [
        // {
        //   label: '承租户',
        //   type: 'select',
        //   selectOptions: this.setOptions('lesseeNo'),
        //   param: 'lesseeNo',
        //   defaultSelect: '',
        //   multiple: false,
        //   isShow: true
        // },
        {
          label: '设施组名称',
          type: 'input',
          param: 'facilityGroupName',
          multiple: false,
          isShow: true
        }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
    }
  },
  computed: {
    facilityTypeList() {
      return this.$store.state.initData.facilityType || [];
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.queryNoGroup();
  },
  methods: {
    //查询未分组设施
    async queryNoGroup() {
      let { data } = await facilityManagement.getFacilityListByConditionAll({
        facilityStatus: false,
        isDistribution: false
      });
      this.notGroupList = data || []
      console.log(data)
    },
    selectionChange(list) {
      this.selectDataList = list
    },
    setOptions(param) {
      let options = [];
      if (param == 'stordocNo') {
        this.$store.state.initData.stordoc.forEach(item => {
          options.push(
            { text: item.stordocName, value: item.stordocNo }
          )
        })
      } else if (param == 'cwhsmanagerName') {
        this.$store.state.initData.person.forEach(item => {
          options.push(
            { text: item.person.name, value: item.person.name }
          )
        })
      } else if (param == "lesseeNo") {
        console.log(this.$store.state.initData.lessesList)
        this.$store.state.initData.lessesList.forEach(item => {
          options.push(
            { text: item.lesseeName, value: item.lesseeNo }
          )
        })
      } else if (param == "facilityType") {
        this.$store.state.initData.facilityType.forEach(item => {
          options.push(
            { text: item.facilityCategory, value: item.facilityCategory }
          )
        })
      } else if (param == "facility") {
        this.$store.state.initData.allFacility.forEach(item => {
          options.push(
            { text: item.facilityName, value: item.facilityNo }
          )
        })
      }
      return options;
    },
    changegroupStatus(row) {
      this.form = {
        facilityGroupNo: row.facilityGroupNo,
        groupStatus: row.groupStatus
      }
      this.$confirm('您确定要继续操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editFalseStatus(this.form)
      }).catch(() => {
        row.groupStatus = !row.groupStatus
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    delData(list = this.selectDataList) {
      let delListNo = []
      list.forEach(item => {
        delListNo.push(item.facilityGroupNo)
      })
      console.log(delListNo)
      this.$confirm('您确定要删除文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await facilityGroup.delList(delListNo)
        if (res.code == 1) {
          this.queryPageByCondition();
          this.queryNoGroup();
          this.$message.success('删除成功');
        } else {
          this.$message.warning('删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    async editFalseStatus(params = {}) {
      let res = await facilityGroup.editFalseStatus(params);
      if (res.code == 1) {
        this.$store.dispatch('initData/queryFacilityGroup');
        this.$message.success('操作成功');
      } else {
        this.$message.success('操作失败');
      }
      this.queryPageByCondition();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectDataList.length > 0) {
          this.delData(this.selectDataList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    async lookView(rowData) {
      let { data } = await facilityManagement.queryFacilityGroup(rowData.facilityGroupNo);
      this.groupFacility = data || [];
      this.dialogTableVisible = true;
      if (this.groupFacility.length == 0) {
        this.$message.warning('该设施组未添加设施')
      }
    },
    search(data) {
      console.log(data)
      this.page = 1;
      this.searchFormData = { ...data }
      this.queryPageByCondition()
    },

    //获取选中Enum
    getEnumEvent(info) {
      this.selectIndex = info.index || 0;
      this.searchFormData.groupStatus = info.data.value;
      this.queryPageByCondition();
      console.log(this.searchFormData)
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          groupStatus: false,
          ...this.searchFormData
        }
      }
      facilityGroup.queryPageByCondition(params).then(res => {
        console.log(res)
        let { data } = res
        this.dataList = data.content || [];
        this.total = data.totalElements;
      }).catch(err => {
        console.log(err)
      })
    },
    // 操作方法
    async handleRow(rowData, item) {
      console.log(rowData, item);
      if (item.flag == 'add') {
        this.groupFacility = []
        this.dialogVisible = true;
      } else if (item.flag == 'edit') {
        let { data } = await facilityManagement.queryFacilityGroup(rowData.facilityGroupNo);
        this.groupFacility = data || [];
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delData([rowData])
      }

      this.addEditFlag = item.flag
    },
    //关闭弹窗
    closeDialog() {
      this.selectDataList = [];
      this.groupFacility = [];
      this.dialogVisible = false;
      this.queryPageByCondition();
      this.queryNoGroup();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.dialogTableVisible = false;
        })
        .catch(_ => { });
    }
  }
};
</script>
<style lang="scss" scoped>
.info {
  box-shadow: 0 0 10px 10px #dddddd5d;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 0 10px 10px #dddddd9f;
  }

  .label {
    padding-bottom: 10px;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333333;
    border-bottom: 1px solid #f0f0f0;
  }

  .invcountDetailInfo {
    display: flex;
    flex-wrap: wrap;
    width: 100%;

    .item {
      width: calc(100% / 3);
      padding-bottom: 10px;
      color: #333333;

      .name {
        color: #333333;
        font-weight: bold;
      }
    }
  }

}
</style>